#!/bin/bash

echo "========================================"
echo "CourseHub 微服务系统 Kubernetes 部署脚本"
echo "========================================"

echo ""
echo "1. 检查 kubectl 连接..."
echo ""
kubectl cluster-info
if [ $? -ne 0 ]; then
    echo "错误: 无法连接到 Kubernetes 集群"
    echo "请确保 kubectl 已正确配置"
    exit 1
fi

echo ""
echo "2. 创建命名空间..."
echo ""
kubectl apply -f k8s/namespace.yaml

echo ""
echo "3. 部署 MySQL 数据库..."
echo ""
kubectl apply -f k8s/mysql-init-configmap.yaml
kubectl apply -f k8s/mysql-deployment.yaml

echo ""
echo "4. 等待 MySQL 启动..."
echo ""
kubectl wait --for=condition=ready pod -l app=mysql -n coursehub-microservices --timeout=300s

echo ""
echo "5. 部署 Consul 服务注册中心..."
echo ""
kubectl apply -f k8s/consul-deployment.yaml

echo ""
echo "6. 等待 Consul 启动..."
echo ""
kubectl wait --for=condition=ready pod -l app=consul -n coursehub-microservices --timeout=300s

echo ""
echo "7. 构建并推送微服务镜像..."
echo ""

# 注意：这里需要根据实际的镜像仓库地址进行调整
echo "请确保已经构建并推送了以下镜像到镜像仓库："
echo "- coursehub/user-management-service:latest"
echo "- coursehub/course-management-service:latest"
echo "- coursehub/exercise-management-service:latest"
echo "- coursehub/learning-progress-service:latest"
echo "- coursehub/api-gateway:latest"
echo ""
echo "如果使用本地镜像，请确保 Kubernetes 集群可以访问这些镜像"
echo ""

echo ""
echo "8. 部署微服务..."
echo ""
kubectl apply -f k8s/user-management-deployment.yaml
kubectl apply -f k8s/course-management-deployment.yaml
kubectl apply -f k8s/exercise-management-deployment.yaml
kubectl apply -f k8s/learning-progress-deployment.yaml

echo ""
echo "9. 部署 API 网关..."
echo ""
kubectl apply -f k8s/api-gateway-deployment.yaml

echo ""
echo "10. 等待所有服务启动..."
echo ""
kubectl wait --for=condition=ready pod -l app=user-management-service -n coursehub-microservices --timeout=300s
kubectl wait --for=condition=ready pod -l app=course-management-service -n coursehub-microservices --timeout=300s
kubectl wait --for=condition=ready pod -l app=exercise-management-service -n coursehub-microservices --timeout=300s
kubectl wait --for=condition=ready pod -l app=learning-progress-service -n coursehub-microservices --timeout=300s
kubectl wait --for=condition=ready pod -l app=api-gateway -n coursehub-microservices --timeout=300s

echo ""
echo "11. 检查部署状态..."
echo ""
kubectl get pods -n coursehub-microservices
kubectl get services -n coursehub-microservices

echo ""
echo "========================================"
echo "部署完成！"
echo ""
echo "服务访问地址："
echo "- Consul UI: http://[node-ip]:30850"
echo "- API Gateway: http://[node-ip]:30800"
echo ""
echo "使用以下命令查看服务状态："
echo "kubectl get pods -n coursehub-microservices"
echo "kubectl get services -n coursehub-microservices"
echo ""
echo "使用以下命令查看日志："
echo "kubectl logs -f deployment/[service-name] -n coursehub-microservices"
echo ""
echo "使用以下命令删除所有资源："
echo "kubectl delete namespace coursehub-microservices"
echo "========================================"